package com.gzsxy.lesson01.udp.liaotian;


import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * udp 接收端
 */
public class UdpReceiveDemo01 {
    public static void main(String[] args) throws Exception {
        //设置接收端的端口
        DatagramSocket socket = new DatagramSocket(6666);

        //不断接收
        while (true) {
            //准备接收包裹
            byte[] container = new byte[1024];

            //得到数据的存储
            DatagramPacket packet = new DatagramPacket(container, 0, container.length);
            socket.receive(packet); //阻塞式接收包裹

            //获取数据
            byte[] data = packet.getData();
            //字节码转为string
            String receiveData = new String(data, 0, data.length);

            //打印数据
            System.out.println(receiveData);
            //如果接收数据字符串有bye 则结束接收
            if (receiveData.equals("bye")) {
                //断开连接，bye
                break;
            }

        }

        socket.close();


    }
}
